import React, { Component } from "react";
import store from "../../redux/store"
import {
    createIncrementAction,
    createDecrementAction,
    createIncrementAsyncAction
} from "../../redux/count_action";

export default class Count extends Component {
    // state = { sum: 0 }

    increment = () => {
        // 获取用户选择的数字
        const { value } = this.numberNode
        // 分发这个action
        store.dispatch(createIncrementAction(value))
    }

    decrement = () => {
        // 获取用户选择的数字
        const { value } = this.numberNode
        // const action = { type: 'increment', data: value * 1 }
        // 分发这个action
        store.dispatch(createDecrementAction(value))
    }

    incrementIfOdd = () => {
        // 获取用户选择的数字
        const { value } = this.numberNode
        if (store.getState() % 2 !== 0) {
            const action = { type: 'increment', data: value * 1 }
            // 分发这个action
            store.dispatch(action)
        }
    }

    incrementAsync = () => {
        // 获取用户选择的数字
        const { value } = this.numberNode
        // 将异步操作交给 action 来做: 所以这里就相当于创建也给异步的方法
        store.dispatch(createIncrementAsyncAction(value, 500))
    }


    render() {
        return (
            <div>
                <h2>当前求和为: {store.getState()}</h2>
                <select ref={ c => this.numberNode = c }>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                </select> &nbsp;
                <button onClick={ this.increment }>+</button> &nbsp;
                <button onClick={ this.decrement }>-</button> &nbsp;
                <button onClick={ this.incrementIfOdd }>奇数再加</button> &nbsp;
                <button onClick={ this.incrementAsync }>异步加</button>
            </div>
        )
    }
}